import http from 'wechat-http'
http.baseURL = "https://live-api.itheima.net"
wx.http = http
http.intercept.request = (params) => {
  // 过滤接口返回的数据
  const app = getApp()
  if (app.token) {
    params.header = {
      Authorization: `Bearer ${app.token}`,
      ...params.header
    }
  }

  return params
}
http.intercept.response = async (res) => {
  // 过滤接口返回的数据
  if (res.statusCode === 401) {
    const app = getApp()
    const result = await http({
      url: '/refreshToken',
      method: 'POST',
      header: {
        Authorization: 'Bearer ' + app.refreshToken,
      }
    })
    // console.log(res);  
    const { token, refreshToken } = result.data
    // console.log(token, refreshToken);
    app.setToken(token, refreshToken)
    return await http({
      ...res.config,
      header: {
        Authorization: 'Bearer ' + token
      }
    })
  }
  return res.data
}

export default http